﻿using Com.Lancetinc.Evs.Cameras;
using System;
using System.Windows.Controls;

namespace Com.Lancetinc.Evs.Controls
{
    public class CameraPropBaseUserControl : UserControl
    {
        public event EventHandler<CameraPropChangeEventArgs> CameraPropChange;

        protected readonly CameraPropViewModel cameraPropViewModel = new ();
        public CameraPropBaseUserControl()
        {
            this.DataContext = cameraPropViewModel;
            cameraPropViewModel.PropertyChanged += CameraPropViewModel_PropertyChanged;
        }

        private void CameraPropViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            this.OnCameraPropChange(e);
            if (!IsInputChanged(e.PropertyName))
            {
                return;
            }
            object newValue = null;
            if (e.PropertyName == nameof(CameraPropViewModel.CameraPropValue))
            {
                newValue = cameraPropViewModel.CameraPropValue;
            }
            else if (e.PropertyName == nameof(CameraPropViewModel.CameraPropAuto))
            {
                newValue = cameraPropViewModel.CameraPropAuto;
            }
            CameraPropChange?.Invoke(this, new CameraPropChangeEventArgs(_cameraProp, e.PropertyName, newValue));
        }

        private CameraProp _cameraProp;

        public CameraProp CameraProp
        {
            set
            {
                _cameraProp = value;
                cameraPropViewModel.SetProp(value);
            }
            get => _cameraProp;
        }

        public void ResetChange(CameraPropChangeEventArgs e)
        {
            if (e.PropertyName.EndsWith("Value"))
            {
                cameraPropViewModel.CameraPropValue = e.Prop.Value;
            }
            else if (e.PropertyName.EndsWith("Auto"))
            {
                cameraPropViewModel.CameraPropAuto = e.Prop.AutoFlag == CameraPropAutoFlag.Auto;
            }
        }

        public void ChangeCameraPropValue(int value)
        {
            cameraPropViewModel.CameraPropValue = value;
        }

        protected virtual void OnCameraPropChange(System.ComponentModel.PropertyChangedEventArgs e)
        {
        }

        private bool IsInputChanged(string propertyName)
        {
            if (_cameraProp == null)
            {
                return false;
            }
            if (propertyName == nameof(CameraPropViewModel.CameraPropValue))
            {
                return _cameraProp.Value != cameraPropViewModel.CameraPropValue;
            }
            if (propertyName == nameof(CameraPropViewModel.CameraPropAuto))
            {
                var isAuto = _cameraProp.AutoFlag == CameraPropAutoFlag.Auto;
                return cameraPropViewModel.CameraPropAuto != isAuto;
            }
            return false;
        }
    }
}
